package netty5.demo1;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

/**
 * Created by GanJc on 2015/11/19.
 */
public class TimeServerHandler extends ChannelInboundHandlerAdapter {

    private static final Logger logger = LoggerFactory.getLogger(TimeServerHandler.class);

    private int count = 0;

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        super.channelReadComplete(ctx);
        ctx.flush();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String reqBuf = (String) msg;
        logger.info("服务端收到来自客户端的请求:{},当前count:{}", reqBuf,++count);
        String respStr = "请求错误"+System.getProperty("line.separator") ;
        if("Time".equals(reqBuf)){
            respStr = new Date().toString()+System.getProperty("line.separator") ;
        }
        ByteBuf respBuf = Unpooled.copiedBuffer(respStr.getBytes());
        ctx.write(respBuf);
    }


    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        super.channelRegistered(ctx);
        logger.info("收到一个客户端请求:{}",ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.info("异常信息:{}",cause.getMessage());
        ctx.close();
    }
}
